<?php
namespace app\libraryadmin\controller;
use \think\Db;

class Booktype extends Common
{
	public function index()
	{
		$rs=Db::name("booktype")->order("tid desc")->select();
		$this->assign("type",$rs);
		return $this->fetch();
	}
	public  function typeadd()
	{
		if(request()->isPost())
		{
			$typename=input('param.typename');
			var_dump($typename);
			$rs=Db::name("booktype")->where("typename='$typename'")->select();
			var_dump($rs);
			if($rs)
				$this->error('该类型已存在');
			else{
				$data=['typename'=>input('param.typename')];
				$rs=Db::name("booktype")->insert($data);
				if($rs) $this->success("图书类型添加成功","index");
				else $this->error("图书类型添加失败");
			}
		}
	else return $this->fetch();

	}
	public function deletetype($tid){
		$book=Db::name("books")->where("tid=$tid")->count();
		if($book)
		{
			$this->error("此类型下有图书，删除失败","index");
		}
		$rs=Db::name("booktype")->delete($tid);
		if($rs){
			$this->success("删除成功",'index');
		}
		else $this->error("删除失败");
	}
	public function typeedit()
	{
		$tid=input('param.tid');
		$type=Db::name("booktype")->find($tid);
	    echo json_encode($type);
	}
	public function dotypeedit()
	{
		if(request()->isPost())
		{
			$tid=input('param.tid');
			$typename=input('param.typename');
			$rs=Db::name("booktype")->where("tid=$tid and typename='$typename'")->find();
			if($rs)
			{
				$this->error("未进行修改");
			}
			else{
				$type=Db::name("booktype")->where("tid!=$tid and typename='$typename'")->count();
				if($type)
				{
					$this->error("类型名已存在");
				}
				else{
					$data=['typename'=>"$typename"];
					$t=Db::name("booktype")->where("tid=$tid")->update($data);
					if($t){
						$this->success("修改成功",'index');
					}
					else $this->error("修改失败");
				}
			}
		}
	}
}